<?php
namespace app\middleware\admin;

use app\common\modules\user\services\UserService;
use app\Request;

class UserToken
{

    public function handle(Request $request, \Closure $next)
    {
        $request->user_token = 'UserToken';

        $path = $request->pathinfo();
        if (in_array($path, ['user/login'])) {
            return $next($request);
        }

        $headers = $request->header();

        $token = isset($headers['User-Token']) ? $headers['User-Token'] : '';

        $userToken = (new \app\common\modules\user\model\UserToken)->where('token', $token)->find();
        if (!$userToken || $userToken->expire_at < time()) {
            return die('token 已经失效');
        }

        $user = UserService::getRecord($userToken->user_id);

        $request->user_id = $user->id;
        $request->user = $user;

        return $next($request);
    }
}
